package com.sise.rsc.controller;

import com.sise.rsc.bean.Result;
import com.sise.rsc.entity.Role;
import com.sise.rsc.repository.RoleRepository;
import com.sise.rsc.repository.UserRepository;
import com.sise.rsc.service.RoleService;
import com.sise.rsc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 用户登录
 */
@Controller
public class loginController {


    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private PasswordEncoder passwordEncoder;

    @RequestMapping("/testing/{uuid}")
    public String testing(@PathVariable String uuid, Model model){

        model.addAttribute("id",uuid);
        return "inde5x";
    }
    /**
     * 登录界面
     * @return
     */
    @RequestMapping("/myLogin")
    public String login(){
        return "common/login";
    }

    /**
     * 登录后的初始界面处理
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpSession session){

        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        User user = (User) auth.getPrincipal();
        System.out.println(user.getAuthorities().toString());
        String au = "";
        for (GrantedAuthority authority : user.getAuthorities()) {
            au = authority.getAuthority();
        }


        //获取用户信息
        com.sise.rsc.entity.User sessionUser = userService.findUserByUsername(auth.getName());
        //保存到session
        session.setAttribute("SESSION_USER",sessionUser);

        session.getAttribute("SESSION_USER");
        //根据不同的用户角色，重定向到相应URL
        if (au.equals("ROLE_USER")){
            return "redirect:/customer/index";
        }else if (au.equals("ROLE_KD")){
            return "redirect:courier/index";
        }else if (au.equals("ROLE_ADMIN"))
            return "redirect:admin/index";
        //非法用户
        return "common/error";

    }


}
